﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using DGMResourcesTool.Logic.FileUtil;

namespace DGMResourcesTool.Logic.Config
{
    public class RegexConfigInfo
    {
        public string m_RegexStr;
        public int m_DeleteDir;    // 删除方向,0,从前向后删除;1,从后向前删除.
        public int m_RegexLength;
    }
    public class RegexConfigUtility
    {
        private static bool _isRegexInit = false;
        private static readonly List<RegexConfigInfo> RegexList = new List<RegexConfigInfo>();

        /// <summary>
        /// 强制重新加载.
        /// </summary>
        public static void Reload()
        {
            Init(true);
        }

        private static void Init(bool isForceReload = false)
        {
            if (_isRegexInit && !isForceReload)
            {
                return;
            }
            RegexList.Clear();
            string regexFilePath = FileUtility.GetConfigFilePath("regex.txt");
            string[] lines = FileReaderWriterUtility.ReadFile(regexFilePath, Encoding.UTF8);
            foreach (var line in lines)
            {
                RegexConfigInfo regexConfigInfo = new RegexConfigInfo();
                string[] tempStrs = line.Split('#');
                if (tempStrs.Length < 2)
                {
                    LogUtility.AddToLog("正则配置错误" + line);
                    return;
                }
                if (tempStrs.Length == 3)
                {
                    // 配置文件中无注释.
                    regexConfigInfo.m_RegexStr = tempStrs[0];

                    regexConfigInfo.m_DeleteDir = Int32.Parse(tempStrs[1]);
                    regexConfigInfo.m_RegexLength = Int32.Parse(tempStrs[2]);
                    RegexList.Add(regexConfigInfo);
                }
                else if (tempStrs.Length == 4)
                {
                    // 配置文件中有注释.
                    regexConfigInfo.m_RegexStr = tempStrs[1];
                    regexConfigInfo.m_DeleteDir = Int32.Parse(tempStrs[2]);
                    regexConfigInfo.m_RegexLength = Int32.Parse(tempStrs[3]);
                    RegexList.Add(regexConfigInfo);
                }
            }

            _isRegexInit = true;
        }

        /// <summary>
        /// 检测有无后缀,如果有后缀则删除后缀.
        /// </summary>
        public static string DeleteRegex(string str)
        {
            Init();
            string result = string.Empty;
            foreach (var regexConfigInfo in RegexList)
            {
                Match m5 = Regex.Match(str, regexConfigInfo.m_RegexStr);
                if (m5.Success)
                {
                    result = regexConfigInfo.m_DeleteDir == 0 ? str.Remove(0, regexConfigInfo.m_RegexLength) : str.Remove(str.Length - regexConfigInfo.m_RegexLength, regexConfigInfo.m_RegexLength);
                    break;
                }
            }
            return result;
        }
    }
}